package action

import (
	"strings"
	"time"

	"gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/gorm"

	"ssdevice/common/constant"
	"ssdevice/common/enums"
	"ssdevice/common/middleware/mqtt"
	"ssdevice/common/utils"
	"ssdevice/internal/device/models"
)

type Sensor struct {
	Orm *gorm.DB
}

func (action *Sensor) Execute(topic string, jsonData map[string]interface{}) {
	devSn := strings.Split(topic, "/")[3]
	AutoLogin(action.Orm, devSn, jsonData)
	if strings.HasSuffix(topic, "/sensor") {
		// 变量上报 - 主题去掉了post
		sensor := utils.GetFieldFromJson([]string{"data"}, jsonData)
		// 更新实时数据
		if sensor != nil {
			mqtt.DealData(devSn, sensor.(map[string]interface{}), func(mData map[string]interface{}) {
				action.sensorUpdate(devSn, mData)
			}, enums.SensorMsg)
		}
		// 更新dev状态
		updateLiveStatus(action.Orm, devSn)
	}
}

// 测量量sensor更新
func (action *Sensor) sensorUpdate(devSn string, sensor map[string]interface{}) {
	devSensor := &models.SysDevSensor{}
	devSensor.Model.Orm = action.Orm
	if err := devSensor.UpdateDevSensor(devSn, sensor); err != nil {
		logger.Error(err)
		return
	}
	add2HistoryQueue(devSn, sensor, enums.SensorMsg)
}

// 加入历史队列
func add2HistoryQueue(devSn string, data map[string]interface{}, msgType enums.MsgType) {
	cacheData := map[string]interface{}{
		"sn":         devSn,
		"data":       data,
		"updateTime": utils.GetNowTimeStr(),
		"msgType":    msgType,
	}
	dataBytes := utils.MapToBytes(cacheData)
	constant.HisDataQueue.Enqueue(string(dataBytes))
	// 广播已处理数据
	mqtt.MqttClient.Publish(constant.HandledMsgTopic, dataBytes)
}

// 更新活跃状态
func updateLiveStatus(db *gorm.DB, devSn string) {
	dev := &models.SysDev{}
	dev.Model.Orm = db
	if err := dev.UpdateOnlineStatus(devSn, map[string]interface{}{
		"online_status":  enums.Online,
		"last_live_time": time.Now(),
	}); err != nil {
		logger.Error(err)
	}
}
